<html><head>
    <title>Draw square</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="webgl.css" type="text/css">
    
    <script src="sylvester.js" type="text/javascript"></script>
    <script src="glUtils.js" type="text/javascript"></script>
    <script type="text/javascript">
	var canvas;
	var gl;
	var squareVerticesBuffer;
	var mvMatrix;
	var shaderProgram;
	var vertexPositionAttribute;
	var perspectiveMatrix;	
	
	function start ()
	{
		canvas = document.getElementById("glcanvas");
		initWebGL(canvas);
		if(gl)
		{
					
			gl.clearColor(0.0, 0.0, 0.0, 1.0);  // Clear to black, fully opaque
			gl.clearDepth(1.0);                 // Clear everything
			gl.enable(gl.DEPTH_TEST);           // Enable depth testing
			gl.depthFunc(gl.LEQUAL);            // Near things obscure far things
			
			// Initialize the shaders; this is where all the lighting for the
			// vertices and so forth is established.
    
			initShaders();
			
			// Here's where we call the routine that builds all the objects
			// we'll be drawing.
    
			initBuffers();
			
			// Set up to draw the scene periodically.
			drawScene();
			
			setInterval(drawScene, 15);
		}		
	}
	
	function initShaders()
	{
		var fragmentShader = getShader(gl, "shader-fs");
		var vertexShader = getShader(gl, "shader-vs");
		   
		// Create the shader program
		 
		shaderProgram = gl.createProgram();
		gl.attachShader(shaderProgram, vertexShader);
		gl.attachShader(shaderProgram, fragmentShader);
		gl.linkProgram(shaderProgram);
		 
		// If creating the shader program failed, alert
		 
		if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))
		{
			alert("Unable to initialize the shader program.");
		}
		
		gl.useProgram(shaderProgram);
		
		vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
		gl.enableVertexAttribArray(vertexPositionAttribute);		
	}
	
	
	
	function initBuffers()
	{
		squareVerticesBuffer = gl.createBuffer();
		
		gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
		
		var vertices = [
			1.0,  1.0,  0.0,
			-1.0, 1.0,  0.0,
			1.0,  -1.0, 0.0,
			-1.0, -1.0, 0.0
		  ];
		gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);	
		
	}
	
	function drawScene()
	{
		    
	    // Clear the canvas before we start drawing on it.

	  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
	  
	  // Establish the perspective with which we want to view the
	  // scene. Our field of view is 45 degrees, with a width/height
	  // ratio of 640:480, and we only want to see objects between 0.1 units
	  // and 100 units away from the camera.
	  
	  perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0);
	  
	  // Set the drawing position to the "identity" point, which is
	  // the center of the scene.
	  
	  loadIdentity();
	  
	  // Now move the drawing position a bit to where we want to start
	  // drawing the square.
	  
	  mvTranslate([-0.0, 0.0, -6.0]);
	  
	  // Draw the square by binding the array buffer to the square's vertices
	  // array, setting attributes, and pushing it to GL.
	  
	  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
	  gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
	  setMatrixUniforms();
	  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
	}
	
		
	function initWebGL(canvas)
	{
		gl = null;
		try 
		{
			gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
		}
		catch(e){}
		if(!gl)
		{
			alert("unable to initialize Webgl. Your browser may not support it.");
		}
	}
	
	//
	// Matrix utility functions
	//

	function loadIdentity() {
	  mvMatrix = Matrix.I(4);
	}

	function multMatrix(m) {
	  mvMatrix = mvMatrix.x(m);
	}

	function mvTranslate(v) {
	  multMatrix(Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4());
	}

	function setMatrixUniforms() {
	  var pUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
	  gl.uniformMatrix4fv(pUniform, false, new Float32Array(perspectiveMatrix.flatten()));

	  var mvUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
	  gl.uniformMatrix4fv(mvUniform, false, new Float32Array(mvMatrix.flatten()));
	}

	
	//
	// getShader
	//
	// Loads a shader program by scouring the current document,
	// looking for a script with the specified ID.
	//
	function getShader(gl, id) {
	  var shaderScript = document.getElementById(id);
	  
	  // Didn't find an element with the specified ID; abort.
	  
	  if (!shaderScript) {
		return null;
	  }
	  
	  // Walk through the source element's children, building the
	  // shader source string.
	  
	  var theSource = "";
	  var currentChild = shaderScript.firstChild;
	  
	  while(currentChild) {
		if (currentChild.nodeType == 3) {
		  theSource += currentChild.textContent;
		}
		
		currentChild = currentChild.nextSibling;
	  }
	  
	  // Now figure out what type of shader script we have,
	  // based on its MIME type.
	  
	  var shader;
	  
	  if (shaderScript.type == "x-shader/x-fragment") {
		shader = gl.createShader(gl.FRAGMENT_SHADER);
	  } else if (shaderScript.type == "x-shader/x-vertex") {
		shader = gl.createShader(gl.VERTEX_SHADER);
	  } else {
		return null;  // Unknown shader type
	  }
	  
	  // Send the source to the shader object
	  
	  gl.shaderSource(shader, theSource);
	  
	  // Compile the shader program
	  
	  gl.compileShader(shader);
	  
	  // See if it compiled successfully
	  
	  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
		alert("An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader));
		return null;
	  }
	  
	  return shader;
	}
		
    </script>
    
    <!-- Fragment shader program -->

    <script id="shader-fs" type="x-shader/x-fragment">
        void main(void) {
            gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
        }
    </script>
    
    <!-- Vertex shader program -->
    
    <script id="shader-vs" type="x-shader/x-vertex">
      attribute vec3 aVertexPosition;
    
      uniform mat4 uMVMatrix;
      uniform mat4 uPMatrix;
    
      void main(void) {
        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
      }
    </script>
    
    </head>
  
  <body onload="start()">
    <canvas id="glcanvas" width="640" height="480">
      Your browser doesn't appear to support the HTML5 <code>&lt;canvas&gt;</code> element.
    </canvas>
  
</body></html>
